<template>
  <div class="w-full">
    <el-form :model="form" label-width="120px" :label-position="'top'">
      <el-form-item label="标题">
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item label="内容">
        <div style="border: 1px solid #ccc">
          <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
            :mode="mode" />
          <Editor style="height: 300px; overflow-y: hidden;" v-model="form.content" :defaultConfig="editorConfig"
            :mode="mode" @onCreated="handleCreated" />
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang='ts'>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
const editorRef = shallowRef()
const mode = 'default'
const model = defineModel({
  default: {
    title: '',
    content: ''
  }
})
const form = ref(model.value);
watch(() => form.value, (data) => {
  model.value = data;
}, {
  immediate: true,
  deep: true
})
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

</script>

<style></style>
